package com.txc.pay.service.impl;


import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.txc.pay.config.PayConfig;
import com.txc.pay.entity.AccountEntity;
import com.txc.pay.enums.PayType;
import com.txc.pay.mapper.AccountMapper;
import com.txc.pay.service.IAccountService;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 支付商户账号配置表 服务实现类
 * </p>
 *
 * @author TXC
 * @since 2023-12-27
 */
@Service
public class AccountServiceImpl extends ServiceImpl<AccountMapper, AccountEntity> implements IAccountService {

    @Override
    public AccountEntity saveAndUpdate(AccountEntity account, MultipartFile file) {
        if (PayType.getEnum(account.getPayType()) != null) {
            PayConfig payConfig = PayType.getConfig(account.getPayType(), account.getParam());
            if (Objects.requireNonNull(payConfig).verifyParam()){
                if (!file.isEmpty()) {
                    try {
                        payConfig.setMerchantPrivateKey(file.getOriginalFilename());
                        account.setParam(payConfig.toString());
                        account.setPrivateKey(file.getBytes());
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
                if (file.isEmpty() && account.getId() != null) {
                    throw new RuntimeException("参数校验失败");
                }
                if (account.getIsDefault() == 1){
                    this.update(new LambdaQueryWrapper<AccountEntity>().eq(AccountEntity::getIsDefault, 1)
                            .eq(AccountEntity::getPayType, account.getPayType()).eq(AccountEntity::getIsDelete, 0));
                }
                this.saveOrUpdate(account);
            }else {
                throw new RuntimeException("参数校验失败");
            }
        }else {
            throw new RuntimeException("支付类型不存在");
        }
        return account;
    }

    @Override
    public List<AccountEntity> listByUserId(String userId, String payType) {
        LambdaQueryWrapper<AccountEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StrUtil.isNotBlank(userId), AccountEntity::getUserId, userId)
                .eq(StrUtil.isNotBlank(payType), AccountEntity::getPayType, payType).eq(AccountEntity::getIsDelete, 0);
        return this.list(queryWrapper);
    }

    @Override
    public AccountEntity obtainDefaultAccount(String payType) {
        LambdaQueryWrapper<AccountEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AccountEntity::getPayType, payType).eq(AccountEntity::getIsDefault, 1)
                .eq(AccountEntity::getIsDelete, 0);
        AccountEntity account = this.getOne(queryWrapper);
        if (account == null){
            List<AccountEntity> accountEntities = this.listByUserId(null, payType);
            if (!accountEntities.isEmpty()){
                account = accountEntities.get(0);
            }
            if (account == null) {
                throw  new RuntimeException("没有可用的商户号！");
            }
        }
        return account;
    }

    @Override
    public void deleteById(String id) {
        this.removeById(id);
    }

    @Override
    public byte[] getPrivateKeyFile(String id) {
        AccountEntity account = this.getById(id);
        return account.getPrivateKey();
    }

    @Override
    public IPage<AccountEntity> getAccountPage(IPage<AccountEntity> page, String userId) {
        IPage<AccountEntity> page1 = new Page<>(page.getCurrent(), page.getSize());
        LambdaQueryWrapper<AccountEntity> query = new LambdaQueryWrapper<>();
        query.eq(AccountEntity::getUserId, userId);
        return baseMapper.selectPage(page1, query);
    }


}
